package com.yuantu.judiciary.aop;

import com.yuantu.judiciary.manager.AsyncManager;
import com.yuantu.judiciary.manager.factory.AsyncFactory;
import com.yuantu.judiciary.model.domain.SysOperLogDO;
import com.yuantu.judiciary.model.dto.AccountInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * 请求响应日志
 *
 * @author syw
 * @since 2023-06-07
 **/
@Aspect
@Component
@Slf4j
public class LogInterceptor {

    /**
     * 执行拦截
     */
    @Around("execution(* com.yuantu.judiciary.controller.*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 生成请求唯一 id
        String requestId = UUID.randomUUID().toString();
        String url = httpServletRequest.getRequestURI();
        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        String reqParam = "[" + StringUtils.join(args, ", ") + "]";
        // 输出请求日志
        log.info("request start，id: {}, accountId: {}, path: {}, ip: {}, params: {}", requestId,getCurrentAccountId(),
                url, httpServletRequest.getRemoteHost(), reqParam);
        // 执行原方法
        Object result = joinPoint.proceed();
        // 输出响应日志
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        log.info("request end, id: {}, cost: {}ms", requestId, totalTimeMillis);
        // 保存数据库
        SysOperLogDO operLog = new SysOperLogDO();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        operLog.setTitle(className + "." + methodName + "()");
        operLog.setUrl(url);
        operLog.setParam(reqParam);
        operLog.setOperIp(httpServletRequest.getRemoteHost());
        operLog.setStatus("0");
        operLog.setCreatorId(getCurrentAccountId());
        AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        return result;
    }

    /**
     * 获取当前账号 id
     */
    public Long getCurrentAccountId() {
        try {
            if (ObjectUtils.isEmpty(SecurityContextHolder.getContext())
                    || ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication())
                    || ObjectUtils.isEmpty(SecurityContextHolder.getContext().getAuthentication().getPrincipal())
            ) {
                return null;
            } else {
                AccountInfoDTO accountInfo = (AccountInfoDTO) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                return accountInfo.getAccountId();
            }
        } catch (Exception e) {
//            log.error("获取当前账号 id 失败: " + e.getMessage(), e);
        }
        return null;
    }
}
